package com.xcity.game.activity.mooncard;

import java.util.Collection;
import java.util.List;

import com.xcity.db.entity.Player;
import com.xcity.game.activity.ActivityService;
import com.xcity.game.activity2.ActivityIds;
import com.xcity.game.common.Cause;
import com.xcity.game.common.MessageConst;
import com.xcity.game.common.PlayerPool;
import com.xcity.game.event.GameEvents;
import com.xcity.game.mail.MailAttach;
import com.xcity.game.mail.MailService;
import com.xcity.game.player.PlayerService;
import com.xcity.game.recharge.RechargeTemplate;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.push.msg.ActivityStatePush;
import com.xcity.pomelo.request.ActiveYearCardRequest;
import com.xcity.pomelo.request.RefreshCardInfoRequest;
import com.xcity.pomelo.request.YearCardInfoRequest;
import com.xcity.pomelo.response.ActiveYearCardResponse;
import com.xcity.pomelo.response.HintResponse;
import com.xcity.pomelo.response.RefreshCardInfoResponse;
import com.xcity.pomelo.response.YearCardInfoResponse;

import naga.x.App;
import naga.x.event.Event;
import naga.x.event.EventListener;
import naga.x.game.template.TemplateService;
import naga.x.game.time.DayListener;
import naga.x.game.time.TimeUpdater;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.ServiceException;
import naga.x.util.TimeUtils;

@OPHandler
public class MoonCardActivityService extends ActivityService implements EventListener, DayListener{
	
	boolean active = true;
	
	List<RechargeTemplate> rechargeTemplates;
//	TLongObjectHashMap<Player> pid2player = new TLongObjectHashMap<Player>();
	
	public static int WEEKCARD_DAYREWARD_STONE = 300;//60;//周卡每日领钻石
	public static int WEEKCARD_TOTALDAYS = 7;//周卡持续时间(自购买后持续X天)
	public static int MOONCARD_DAYREWARD_STONE = 750;//150;//月卡每日领钻石
	public static int MOONCARD_TOTALDAYS = 30;//月卡持续时间(自购买后持续X天)
	public static int YEARCARD_DAYREWARD_STONE = 500;//100;//2017.04.13//88;//年卡(终身卡)每日领钻石
	public static int YEARCARD_FIRSTREWARD_STONE = 0;//88;//年卡激活时领钻石
	public static int YEARCARD_ACTIVE_RMB = 30;
	public static int[] YEARCARD_DAYREWARD_ITEMS = new int[]{90025};
	
	public static int WEEKCARD_TEMP_ID = 30011;
	public static int MOONCARD_TEMP_ID = 30012;
	public static int YEARCARD_TEMP_ID = 30014;
	
	@Override
	public void startup() throws ServiceException {
		rechargeTemplates = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(RechargeTemplate.class);
		App.getApp().getEventManager().register(this);
		TimeUpdater.getInstance().addDayListener(this);
	}

	@Override
	public void shutdown() throws ServiceException {
	}

	@Override
	public int[] getEventTypes() {
		return new int[]{
				GameEvents.EVENT_PLAYER_LOADED,
				GameEvents.EVENT_PLAYER_LOGIN,
				GameEvents.EVENT_PLAYER_LOGOUT,
				GameEvents.EVENT_RECHARGE,
				GameEvents.EVENT_RECHARGE_OFFLINE
				};
	}

	@Override
	public void handleEvent(Event event) {
		switch (event.getType()) {
		case GameEvents.EVENT_PLAYER_LOADED:
			playerLoaded(event.getParameter());
			break;
		case GameEvents.EVENT_PLAYER_LOGIN:
			playerLogin(event.getParameter());
			break;
//		case GameEvents.EVENT_PLAYER_LOGOUT:
//			playerLogout(event.getParameter());
//			break;
		case GameEvents.EVENT_RECHARGE:
		case GameEvents.EVENT_RECHARGE_OFFLINE:
			handleRecharge((Player)event.getParameter(0), (int)event.getParameter(1), (RechargeTemplate)event.getParameter(2));
			break;
		}
	}

	@Override
	public boolean dayChanged() {
		Collection<Player> players = App.getApp().getServiceManager().get(PlayerService.class).getOnlinePlayers();
		for(Player player : players){
			tryGetReward(player);
		}
//		long keys[] = pid2player.keys();
//		for(int i = 0; i < keys.length; i++){
//			Player player = pid2player.get(keys[i]);
//			tryGetReward(player);
//		}
		return true;
	}
	
	public void playerLogin(Player player){
//		if(!pid2player.contains(player.getId())){
//			pid2player.put(player.getId(), player);
//		}
		tryGetReward(player);
	}
	
	public void playerLoaded(Player player){
////////start
//		int needRecharge = -1;
//		if(player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0) <= 0){
//			needRecharge = MoonCardActivityService.YEARCARD_ACTIVE_RMB - player.getPool().getInt(PlayerPool.PROPERTY_YEAR_CARD_TOTAL_RECHARGE, 0);
//			if(needRecharge <= 0){
//				needRecharge = 0;
//			}
//		}
//		if(needRecharge != -1){
//			player.send(new ActivityStatePush(ActivityIds.ACTIVITY_MOONCARD, STATE_OPENED));
//		}
////////end
//		int lastRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
//		if(lastRecharge == 0){
//		}
		player.send(new ActivityStatePush(ActivityIds.ACTIVITY_MOONCARD, STATE_OPENED));
	}
	
	public void playerLogout(Player player){
//		pid2player.remove(player.getId());
	}

	public RechargeTemplate getRechargeTemplateById(int tempId){
		RechargeTemplate temp = null;
		for(int i = 0; i < rechargeTemplates.size(); i++){
			if(rechargeTemplates.get(i).getId() == tempId){
				temp = rechargeTemplates.get(i);
				break;
			}
		}
		return temp;
	}
	
	public void handleRecharge(Player player, int money, RechargeTemplate template){
		if(!active){
			return;
		}
		int today = TimeUpdater.getInstance().today();
////////----start
//		int lastRechargeYear = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
//		if(lastRechargeYear <= 0){
//			//未激活
//			int totalRecharge = player.getPool().getInt(PlayerPool.PROPERTY_YEAR_CARD_TOTAL_RECHARGE, 0);
//			totalRecharge = totalRecharge + money;
//			player.getPool().put(PlayerPool.PROPERTY_YEAR_CARD_TOTAL_RECHARGE, totalRecharge);
////			if(totalRecharge >= YEARCARD_ACTIVE_RMB){
////				int syncValue = YEARCARD_ACTIVE_RMB - player.getPool().getInt(PlayerPool.PROPERTY_YEAR_CARD_TOTAL_RECHARGE, 0);
////				if(syncValue <= 0){
////					syncValue = 0;
////				}
////			}
//		}
////////----end
		
		if(template.getId() == WEEKCARD_TEMP_ID){
			int lastWeekRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, 0);
			int weekTotalDays = player.getPool().getInt(PlayerPool.PROPERTY_WEEK_CARD_TOTALDAY, 0);
			if(lastWeekRecharge > 0 && weekTotalDays > 0){
				if(!(TimeUtils.checkDayDuring(lastWeekRecharge, today, weekTotalDays + 1))){//today > lastWeekRecharge + weekTotalDays
					//过期
					player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, today);
					player.getPool().put(PlayerPool.PROPERTY_WEEK_CARD_TOTALDAY, WEEKCARD_TOTALDAYS);
				}else{
					weekTotalDays = weekTotalDays + WEEKCARD_TOTALDAYS;
					player.getPool().put(PlayerPool.PROPERTY_WEEK_CARD_TOTALDAY, weekTotalDays);
				}
			}else{
				player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, today);
				player.getPool().put(PlayerPool.PROPERTY_WEEK_CARD_TOTALDAY, WEEKCARD_TOTALDAYS);
			}
			
//			MailAttach attach = new MailAttach(0, template.getStone());
//			String title = "购买周卡奖励";
//			String content = "";
//			App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
			LOG.info("[MOONREWARD]ID[{}]STONE[{}]CAUSE[{}]", player.getId(), template.getStone(), Cause.WEEK_CARD_FIRSTREWARD);
		}else if(template.getId() == MOONCARD_TEMP_ID){
			int lastMoonRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, 0);
			int moonTotalDays = player.getPool().getInt(PlayerPool.PROPERTY_MOON_CARD_TOTALDAY, 0);
			if(lastMoonRecharge > 0 && moonTotalDays > 0){
				if(!(TimeUtils.checkDayDuring(lastMoonRecharge, today, moonTotalDays + 1))){//today > lastMoonRecharge + moonTotalDays
					player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, today);
					player.getPool().put(PlayerPool.PROPERTY_MOON_CARD_TOTALDAY, MOONCARD_TOTALDAYS);
				}else{
					moonTotalDays = moonTotalDays + MOONCARD_TOTALDAYS;
					player.getPool().put(PlayerPool.PROPERTY_MOON_CARD_TOTALDAY, moonTotalDays);
				}
			}else{
				player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, today);
				player.getPool().put(PlayerPool.PROPERTY_MOON_CARD_TOTALDAY, MOONCARD_TOTALDAYS);
			}
//			MailAttach attach = new MailAttach(0, template.getStone());
//			String title = "购买月卡奖励";
//			String content = "";
//			App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
			LOG.info("[MOONREWARD]ID[{}]STONE[{}]CAUSE[{}]", player.getId(), template.getStone(), Cause.MOON_CARD_FIRSTREWARD);
		}else if(template.getId() == YEARCARD_TEMP_ID){
			//TODO
			int lastYearRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
			if(lastYearRecharge == 0){
				//领取
				MailAttach attach = new MailAttach();//0, YEARCARD_FIRSTREWARD_STONE
				String title = "终身卡每日奖励";
				String content = "恭喜您获得终身卡奖励";
				if(YEARCARD_DAYREWARD_ITEMS.length > 0){
					for(int i = 0; i < YEARCARD_DAYREWARD_ITEMS.length; i++){
						attach.addItem(YEARCARD_DAYREWARD_ITEMS[i], 1);
					}
				}
				App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
				LOG.info("[MOONREWARD]ID[{}]STONE[{}]CAUSE[{}]", player.getId(), YEARCARD_FIRSTREWARD_STONE, Cause.YEAR_CARD_FIRSTREWARD);
//			lastYearRecharge = today;
				player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, today);
//				player.send(new ActivityStatePush(ActivityIds.ACTIVITY_MOONCARD, STATE_CLOSED));
			}

		}
	}

	@PomeloOP(PomeloRoute.REFRESH_CARD)
	protected void requestRefreshCard(Session session, RefreshCardInfoRequest req){
		Player player = session.getClient();
		int weekday = 0;
		int moonday = 0;
		int yearday = 0;
		int today = TimeUpdater.getInstance().today();
		int lastWeekRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, 0);
		int weekTotalDays = player.getPool().getInt(PlayerPool.PROPERTY_WEEK_CARD_TOTALDAY, 0);
		weekday = TimeUtils.getDayGap(today, lastWeekRecharge + weekTotalDays);
		if(weekday < 0){
			weekday = 0;
		}

		int lastMoonRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, 0);
		int moonTotalDays = player.getPool().getInt(PlayerPool.PROPERTY_MOON_CARD_TOTALDAY, 0);
		moonday = TimeUtils.getDayGap(today, lastMoonRecharge + moonTotalDays);
		if(moonday < 0){
			moonday = 0;
		}

		int lastYearRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
		if(lastYearRecharge > 0){
			yearday = 1;
		}
		player.send(new RefreshCardInfoResponse(req.getSerial(), weekday, moonday, yearday));
	}
	
	public void tryGetReward(Player player){
		if(!active){
			return;
		}
		int today = TimeUpdater.getInstance().today();
		
		int lastWeekRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, 0);
		int weekTotalDays = player.getPool().getInt(PlayerPool.PROPERTY_WEEK_CARD_TOTALDAY, 0);
		int lastGetWeekReward = player.getPool().getInt(PlayerPool.PROPERTY_LAST_GET_REWARD_WEEK, 0);
		if(lastWeekRecharge > 0 && weekTotalDays > 0){
			if(TimeUtils.checkDayDuring(lastWeekRecharge, today, weekTotalDays + 1)){//today <= lastWeekRecharge + weekTotalDays
				//在周内
				if(lastGetWeekReward != today && today > lastWeekRecharge){
					//未领
					MailAttach attach = new MailAttach(0, WEEKCARD_DAYREWARD_STONE);
					String title = "每日周卡奖励";
					String content = null;
					if(!TimeUtils.checkDayDuring(lastWeekRecharge, today, weekTotalDays)){//lastWeekRecharge + weekTotalDays - 1 < today
						content = "您的周卡即将到期，每日钻石福利即将离您而去，若希望保留请购卡。";
					}else{
						content = "恭喜您获得周卡每日钻石奖励，祝您有个好心情！游戏愉快！";
					}
					App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
					LOG.info("[MOONREWARD]ID[{}]STONE[{}]CAUSE[{}]", player.getId(), WEEKCARD_DAYREWARD_STONE, Cause.WEEK_CARD_DAYREWARD);
					player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_WEEK, today);
				}
			}
		}
		
		int lastMoonRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, 0);
		int moonTotalDays = player.getPool().getInt(PlayerPool.PROPERTY_MOON_CARD_TOTALDAY, 0);
		int lastGetMoonReward = player.getPool().getInt(PlayerPool.PROPERTY_LAST_GET_REWARD_MOON, 0);
		if(lastMoonRecharge > 0 && moonTotalDays > 0){
			if(TimeUtils.checkDayDuring(lastMoonRecharge, today, moonTotalDays + 1)){//today <= lastMoonRecharge + moonTotalDays
				//在月内
				if(lastGetMoonReward != today && today > lastMoonRecharge){
					//未领
					MailAttach attach = new MailAttach(0, MOONCARD_DAYREWARD_STONE);
					String title = "每日月卡奖励";
					String content = null;
					if(!TimeUtils.checkDayDuring(lastMoonRecharge, today, moonTotalDays - 2)){//lastMoonRecharge + moonTotalDays - 3 < today
						content = "您的月卡即将到期，每日钻石福利即将离您而去，若希望保留请购卡。";
					}else{
						content = "恭喜您获得月卡每日钻石奖励，祝您有个好心情！游戏愉快！";
					}
					App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
					LOG.info("[MOONREWARD]ID[{}]STONE[{}]CAUSE[{}]", player.getId(), MOONCARD_DAYREWARD_STONE, Cause.MOON_CARD_DAYREWARD);
					player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_MOON, today);
				}
			}
		}
		
		int lastYearRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
		int lastGetYearReward = player.getPool().getInt(PlayerPool.PROPERTY_LAST_GET_REWARD_YEAR, 0);
		if(lastYearRecharge > 0){
			if(lastGetYearReward != today && today > lastYearRecharge){
				MailAttach attach = new MailAttach(0, YEARCARD_DAYREWARD_STONE);
				String title = "终身卡每日奖励";
				String content = "恭喜您获得终身卡奖励";
				if(YEARCARD_DAYREWARD_ITEMS.length > 0){
					for(int i = 0; i < YEARCARD_DAYREWARD_ITEMS.length; i++){
						attach.addItem(YEARCARD_DAYREWARD_ITEMS[i], 1);
					}
				}
				App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
				LOG.info("[MOONREWARD]ID[{}]STONE[{}]CAUSE[{}]", player.getId(), YEARCARD_DAYREWARD_STONE, Cause.YEAR_CARD_DAYREWARD);
				player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_YEAR, today);
			}
		}
	}
	@Deprecated
//	@PomeloOP(PomeloRoute.ACTIVITY_MOON_REQUEST_ACTIVE_YEAR)
	protected void requestActiveYearCard(Session session, ActiveYearCardRequest req){
		Player player = session.getClient();
		if(player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0) > 0){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_MOON_ACTIVED));
			return;
		}
//		int lastYearRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
		int yearTotalRecharge = player.getPool().getInt(PlayerPool.PROPERTY_YEAR_CARD_TOTAL_RECHARGE, 0);
		if(yearTotalRecharge < YEARCARD_ACTIVE_RMB){
			player.send(new HintResponse(req.getSerial(), MessageConst.ACTIVITY_MOON_RECHARGE_NOT_ENOUGH));
			return;
		}
		//领取
		int today = TimeUpdater.getInstance().today();	
		MailAttach attach = new MailAttach(0, YEARCARD_FIRSTREWARD_STONE);
		String title = "终身卡每日奖励";
		String content = "恭喜您获得终身卡奖励";
		if(YEARCARD_DAYREWARD_ITEMS.length > 0){
			for(int i = 0; i < YEARCARD_DAYREWARD_ITEMS.length; i++){
				attach.addItem(YEARCARD_DAYREWARD_ITEMS[i], 1);
			}
		}
		App.getApp().getServiceManager().get(MailService.class).sendSystemMail(player.getId(), title, content, attach);
		LOG.info("[MOONREWARD]ID[{}]STONE[{}]CAUSE[{}]", player.getId(), YEARCARD_FIRSTREWARD_STONE, Cause.YEAR_CARD_FIRSTREWARD);
//		lastYearRecharge = today;
		player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, today);
		player.send(new ActiveYearCardResponse(req.getSerial(), -1));
//		player.send(new ActivityStatePush(ActivityIds.ACTIVITY_MOONCARD, STATE_CLOSED));
	}

	@Deprecated
//	@PomeloOP(PomeloRoute.ACTIVITY_MOON_REQUEST_YEAR_INFO)
	protected void requestYearInfo(Session session, YearCardInfoRequest req){
		Player player = session.getClient();
		int needRecharge = -1;
		if(player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0) <= 0){
			needRecharge = MoonCardActivityService.YEARCARD_ACTIVE_RMB - player.getPool().getInt(PlayerPool.PROPERTY_YEAR_CARD_TOTAL_RECHARGE, 0);
			if(needRecharge <= 0){
				needRecharge = 0;
			}
		}
		player.send(new YearCardInfoResponse(req.getSerial(), needRecharge));
	}
	
	@Deprecated
	public void tryPassDay(Player player, int getReward){
		int lastYearRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
		int lastGetYearReward = player.getPool().getInt(PlayerPool.PROPERTY_LAST_GET_REWARD_YEAR, 0);

		int lastWeekRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, 0);
		int lastGetWeekReward = player.getPool().getInt(PlayerPool.PROPERTY_LAST_GET_REWARD_WEEK, 0);
		
		int lastMoonRecharge = player.getPool().getInt(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, 0);
		int lastGetMoonReward = player.getPool().getInt(PlayerPool.PROPERTY_LAST_GET_REWARD_MOON, 0);
		
		if(lastYearRecharge > 0){
			player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, lastYearRecharge - 1);
		}
		if(lastGetYearReward > 0){
			player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_YEAR, lastGetYearReward - 1);
		}
		if(lastWeekRecharge > 0){
			player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, lastWeekRecharge - 1);
		}
		if(lastGetWeekReward > 0){
			player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_WEEK, lastGetWeekReward - 1);
		}
		if(lastMoonRecharge > 0){
			player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, lastMoonRecharge - 1);
		}
		if(lastGetMoonReward > 0){
			player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_MOON, lastGetMoonReward - 1);
		}
		if(getReward == 0){
			tryGetReward(player);
		}
	}
	
	@Deprecated
	public void resetMoonCard(Player player){
		player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_YEAR, 0);
		player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_YEAR, 0);
		player.getPool().put(PlayerPool.PROPERTY_YEAR_CARD_TOTAL_RECHARGE, 0);
		
		player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_WEEK, 0);
		player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_WEEK, 0);
		player.getPool().put(PlayerPool.PROPERTY_WEEK_CARD_TOTALDAY, 0);
		
		player.getPool().put(PlayerPool.PROPERTY_LAST_RECHARGE_MOON, 0);
		player.getPool().put(PlayerPool.PROPERTY_LAST_GET_REWARD_MOON, 0);
		player.getPool().put(PlayerPool.PROPERTY_MOON_CARD_TOTALDAY, 0);
	}
}
